<template>
  <div class="box">
    <!-- 左右控制栏 -->
    <div class="controler">
      <PageControler 
      @toOrigin="toOrigin"
      @show3DTiles="show3DTiles"
      @hidden3DTiles="hidden3DTiles"
      @isTextShow="isTextShow"
      @toEntity="toEntity"
      ></PageControler>
      <!-- 头部标题区域 -->
      <PageHead 
      @showFlood="showFlood"
      ></PageHead>
      <div class="block" v-if="showFlowTool">
        <i class="el-icon-video-play" @click="start"  v-if="video"></i>
        <i class="el-icon-video-pause"  @click="pause" v-if="pause1"></i>
        <!-- 进度条和per绑定 表示百分比 -->
        <el-slider v-model="per" class="long" :format-tooltip="formatTooltip"></el-slider><span class="long2">{{per}}%</span>
      </div>
      <!-- 淹没分析面板 -->
      <div class="flood" v-show="showFlowTool"  >
          <div class="i">
            <i class="el-icon-close" @click="hideFlood"></i >
          </div>
          <div class="flood-item">
            <label>最大高度:</label>
            <input type="number" v-model="maxFlood">
          </div>
          <div class="flood-item">
            <label>最小高度:</label>
            <input type="number" v-model="miniFlood">
          </div>
          <div class="flood-item">
            <label>当前高度</label>
            <input type="number" v-model="nowFlood"  disabled>
          </div>
          <div class="flood-item">
            <label>目标淹没高度:  </label>
            <input type="number" v-model="tarFlood">
          </div>
          <div class="flood-item">
            <label class="bottom">淹没速度:</label>
            <input type="number" v-model="speed">
          </div>
          <div class="btns">
            <button @click="startFlowing();showactive1()" class="btn1">开始</button>
            <button @click="clearFlowing();showactive2()">清除</button>
            <button id="btn3" :class="[isChange3 ? 'active' : 'unactive']" @click="draw_polygon();showactive3()">绘制淹没范围</button>
          </div>
      </div>
    </div>
    <Users></Users>
    <div id="container"></div>
  </div>
</template>

<script>
// 引入全局变量
import global from '../views/Global.vue'
// 引入mixin
import coverage from '@/mixins/addcCoverages.js'
// 引入组件
import DivLabel from '@/utils/divLabel'
import PageControler from './HomePage/PageControler.vue'
import PageHead from './HomePage/PageHead.vue'
import VideoControler from './HomePage/VideoControler.vue'
import Users from './HomePage/Users.vue'
let per = 0
let nowFlood=0
export default {
  components:{
    PageControler,
    PageHead,
    VideoControler,
    Users
  },
  mixins:[coverage],
  data() {
    return {
      tileset:null,
      polyLinePoints:{
        // 右岸小堡拦河闸下游段护岸改造1.265km第一段
        polyline_1:[
          123.805485, 41.321242,
          123.805376, 41.320867,
          123.805342, 41.320554,
          123.805244, 41.319943,
          123.805285, 41.319521,
          123.805317, 41.319127,
          123.805326, 41.318724,
          123.805374, 41.318108,
          123.80536, 41.31754,
          123.805373, 41.316978,
          123.80531, 41.316559,
          123.805261, 41.316253,
          123.805022, 41.315692,
          123.804873, 41.315271,
          123.804549, 41.314654,
          123.80429, 41.314177,
          123.804009, 41.313838,
          123.803759, 41.313503,
          123.803387, 41.313135,
          123.803001, 41.312803,
          123.802501, 41.312485,
          123.802205, 41.312312,
          123.801663, 41.312071,
          123.801313, 41.311993,
          123.800804, 41.311822,
          123.800132, 41.311604
        ],
        // 右岸小堡拦河闸下游段护岸改造1.265km第二段
        polyline_2:[
          123.802078, 41.309775,
          123.802271, 41.309819,
          123.802515, 41.30988,
          123.802762, 41.309936,
          123.80295, 41.309978,
          123.803119, 41.310011,
          123.803416, 41.310061
        ],
        // 合金沟两岸新建回水堤共计135m[left]
        polyline_3:[
          123.794962, 41.306173,
          123.794892, 41.306295,
          123.794829, 41.30642,
          123.79476, 41.306539,
          123.794739, 41.306588,
          123.794715, 41.306656,
          123.794704, 41.30673,
          123.794695, 41.306789
        ],
        // 合金沟两岸新建回水堤共计135m[right] 
        polyline_4:[
          123.795101, 41.306772,
          123.795153, 41.306718,
          123.795195, 41.306671,
          123.79523, 41.306627,
          123.795278, 41.306557,
          123.795326, 41.306481,
          123.795375, 41.306393,
          123.795433, 41.306301
        ],
        // '左岸小堡公园段护岸改造1.142km'
        polyline_5:[
          123.808487, 41.32094,
          123.808527, 41.320466,
          123.808562, 41.319797,
          123.808622, 41.319398,
          123.808686, 41.318586,
          123.808691, 41.318175,
          123.808638, 41.317776,
          123.808553, 41.317305,
          123.808492, 41.316778,
          123.808398, 41.316421,
          123.808391, 41.316034,
          123.808063, 41.315431,
          123.807688, 41.314806,
          123.807308, 41.314147,
          123.806709, 41.31328,
          123.806155, 41.312562,
          123.805795, 41.312026,
          123.80544, 41.311451
        ],
        // 丹阜高速至威宁大桥段护岸改造0.605km
        polyline_6:[
          123.80972, 41.330001,
          123.810045, 41.330332,
          123.810307, 41.330589,
          123.810606, 41.330921,
          123.81095, 41.331247,
          123.811287, 41.331578,
          123.811663, 41.331938,
          123.811919, 41.3322,
          123.812123, 41.332425,
          123.812401, 41.332591,
          123.812805, 41.332831,
          123.813159, 41.332989,
          123.813521, 41.333189,
          123.81395, 41.333411,
          123.814334, 41.333627,
          123.814736, 41.333838
        ],
        // 左岸本钢厂区段护岸改造2.914km[0]
        polyline_7:[
          123.710825, 41.275711,
          123.711183, 41.275905,
          123.711643, 41.276152,
          123.712124, 41.276417,
          123.712543, 41.276634,
          123.713125, 41.276952,
          123.713658, 41.277249,
          123.713959, 41.277417,
          123.714954, 41.27797,
          123.715505, 41.278265,
          123.716446, 41.278774,
          123.717514, 41.279405,
          123.718529, 41.27997,
          123.719339, 41.28042,
          123.720683, 41.281204,
          123.721748, 41.281824,
          123.722473, 41.28231
        ],
        // 左岸本钢厂区段护岸改造2.914km[2]
        polyline_8:[
          123.72345, 41.282869,
          123.72385, 41.283108,
          123.72439, 41.283474,
          123.724857, 41.283755,
          123.725336, 41.284066,
          123.725988, 41.284477,
          123.726653, 41.284929,
          123.727396, 41.285428,
          123.727924, 41.285801,
          123.728623, 41.286269,
          123.729354, 41.286777,
          123.730276, 41.287363,
          123.730938, 41.287813,
          123.73159, 41.288245,
          123.732333, 41.288725,
          123.733095, 41.289205,
          123.733854, 41.289692,
          123.734456, 41.290098,
          123.734988, 41.290423,
          123.735693, 41.290847,
          123.736423, 41.291425,
          123.737159, 41.292008,
          123.737653, 41.2924
        ],
        // 左岸爱之滩公园段护岸改造1.502km
        polyline_9:[
        123.758355,  41.310274,
        123.758784,  41.310728,
        123.759918,  41.311454,
        123.761874,  41.312667,
        123.763672,  41.313248,
        123.764585,  41.313878,
        123.765963,  41.314588,
        123.767346,  41.315252,
        123.768613,  41.315841,
        123.769893,  41.316251,
        123.770769,41.31625,
        123.771321,  41.316228,
        123.773325,  41.315593,
        ],
        // 右岸溪湖河口上游段护岸改造0.6 km[0]
        polyline_10:[
          123.771197,41.319125,
          123.771456,41.319103,
          123.771648,41.3191,
          123.771893,41.319057,
          123.77214,41.319037,
          123.772489,41.318996,
          123.772635,41.318978,
          123.772838,41.318948,
          123.773029,41.31891,
          123.77316,41.318838,
          123.77345,41.318709,
          123.773633,41.318603,
          123.773841,41.3185,
          123.774143,41.318334,
          123.774369,41.318191,
          123.774655,41.31804,
          123.774926,41.317922,
        ],
        // 右岸溪湖河口上游段护岸改造0.6 km[1]
        polyline_11:[
          123.77519, 41.317792,
          123.775395, 41.317677,
          123.775594, 41.317575,
          123.775762, 41.317466,
          123.776013, 41.317311,
          123.776172, 41.317203,
          123.77634, 41.317096,
          123.776426, 41.317018,
          123.776551, 41.316929,
          123.776756, 41.316845,
          123.777234, 41.316716
        ],
        // 右岸衍水大桥至溪湖桥段堤防加固1.918km
        polyline_12:[
        123.746312,  41.304662,
        123.748496,  41.306321,
        123.75207,  41.309137,
        123.754741,  41.311051,
        123.758297,  41.313849,
        123.761357,  41.314499,
        ],
        // 新建防洪墙238m、回水堤470m[0]
        polyline_13:[
          123.806841, 41.310302,
          123.807034, 41.310594,
          123.807291, 41.310955,
        ],
        // 新建防洪墙238m、回水堤470m[1]
        polyline_14:[
          123.806126, 41.309972,
          123.805822, 41.309036,
          123.805568,41.308081,
          123.805538, 41.307302,
        ],
        // 新建防洪墙238m、回水堤470m[2]
        polyline_15:[
          123.803868, 41.309819,
          123.804888, 41.309922,
          123.805808, 41.309956,
          123.805729, 41.309356,
        ],
      },
      labelStr:{
        str1:'小堡拦河闸下游段护岸改造1.265km',
        str2:'合金沟两岸新建回水堤共计135m',
        str3:'左岸峪溪桥下游段新建护脚0.117km',
        str4:'左岸小堡公园段护岸改造1.142km',
        str5:'丹阜高速至威宁大桥段护岸改造0.605km',
        str6:'左岸本钢厂区段护岸改造2.914km',
        str7:'左岸爱之滩公园段护岸改造1.502km',
        str8:'右岸溪湖河口上游段护岸改造0.6km',
        str9:'右岸衍水大桥至溪湖桥段堤防加固1.918km',
        str10:'新建防洪墙238m、回水堤470m',
      },
      strPosition:[
        [123.804895, 41.315485],
        [123.79503, 41.306518],
        [123.801267, 41.308146],
        [123.806777, 41.313413],
        [123.8129, 41.332935],
        [123.720192, 41.280666],
        [123.763425,41.313056],
        [123.771368, 41.319211],
        [123.749915, 41.307397],
        [123.806194, 41.30897],
      ],
      // 控制施工信息展示
      isShow:1,
      // 控制洪水模拟展示
      showFlowTool:false,
      active:false,
      // 点击按钮变色
      isChange1:false,
      isChange2:false,
      isChange3:false,
      // 淹没分析最大高度
      maxFlood:0,
      // 最小高度
      miniFlood:0,
      // 当前高度
      nowFlood:0,
      // 目标高度
      tarFlood:0,
      // 淹没速度
      speed:0.5,
      terrainProvider: null,
      // 是否第一次添加淹没分析
      isFirst:true,
      // 淹没分析坐标点[{}]
      tempPoints:[], 
      // 进度条百分比
      per:0,
      // 开始播放
      video:true,
      // 暂停播放
      pause1:false,

    }
  },
  mounted() {
    this.init()
    this.getpoint()
    // this.getEarthPoint(e)
  },
  methods: {
    // 初始化地图
    init(){
      Cesium.Ion.defaultAccessToken ="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmZmU4ODg5MS1mYTYxLTQ1MTMtOTM1My03YzhhMTM3ZWUxNDAiLCJpZCI6MTIyNTgyLCJpYXQiOjE2NzQ5NjQ0ODR9.e9Q99Z21wt6NjtUEtGHIjYoNq8WGHsisnoysbVptffE";
      var tiandituTk='4b418047223bdd0dfc7cbdb7dfe1d3e6'
      global.terrainProvider = Cesium.createWorldTerrain()
      // 服务负离子域
      const subdomains=['0','1','2','3','4','5','6','7']
      // 底图
      global.defaultLayer=new Cesium.WebMapTileServiceImageryProvider({
        //影像底图
        url: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer",
        subdomains: subdomains,
        layer: "tdtImgLayer",
        style: "default",
        format: "image/jpeg",
        tileMatrixSetID: "GoogleMapsCompatible",//使用谷歌的瓦片切片方式
        show: true,
      })
      global.viewer = new Cesium.Viewer('container', {
        // 关闭原生控件
        geocoder:false, // 搜索功能
        homeButton:false, // 视角恢复功能
        sceneModePicker:false, // 2d、3d切换功能
        baseLayerPicker:false, // 地图底色选择功能
        navigationHelpButton:false, // 帮助功能
        animation:false, // 动画功能
        timeline:false, // 时间线功能
        fullscreenButton:false, // 全屏功能
        shouldAnimate: false, // 太阳模拟时钟时间
        // clockViewModel: new Cesium.ClockViewModel(clock),
        // 在线地形
        terrainProvider: global.terrainProvider,
        infoBox: false, // 关闭点击信息弹窗
     })
     global.viewer.scene.postProcessStages.fxaa.enabled = false;
      this.show3DTiles()
      // global.viewer.camera.flyTo({
      //   destination: Cesium.Cartesian3.fromDegrees(123.76629,41.304862,10000)
      // })
      global.viewer.flyTo(global.viewer.tileset)
      global.viewer.scene.globe.enableLighting = true;//true：360度地球有亮和黑的区分，亮和黑的影像地图亮度是一样的// 取消鼠标双击追踪事件
 
      global.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
      global.viewer.shadows = false;//是否显示阴影
      // global.viewer.scene.globe.depthTestAgainstTerrain = true
      // 获取鼠标点击坐标
      return global.viewer
    },
    // 返回到倾斜摄影原点
    toOrigin(){
      global.viewer.flyTo(global.viewer.tileset)
    },
    toEntity(){
      global.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(123.773716, 41.29558,10000),
        orientation: {
          heading: Cesium.Math.toRadians(0), // 水平偏角，默认正北 0
          pitch: Cesium.Math.toRadians(-90), // 俯视角，默认-90，垂直向下
          roll: 0, // 旋转角
        },
      })
    },
    // 展示倾斜摄影
    show3DTiles(){
      const tileset = new Cesium.Cesium3DTileset({
        url: "http://120.46.72.236:9003/model/ELiezQGm/tileset.json",
        // loadSiblings: true,// 如果为true则不会在已加载完概况房屋后，自动从中心开始超清化房屋
        // maximumScreenSpaceError: 64, // 数值加大，能让最终成像变模糊
        // cullRequestsWhileMovingMultiplier: 10,// 值越小能够更快的剔除
        // maximumMemoryUsage: 128,// 内存分配变小有利于倾斜摄影数据回收，提升性能体验
        // progressiveResolutionHeightFraction: 0.5, // 数值偏于0能够让初始加载变得模糊
        // dynamicScreenSpaceErrorDensity: 0.1, // 数值加大，能让周边加载变快
        // dynamicScreenSpaceErrorFactor: 1, 
        // dynamicScreenSpaceError: true // 有了这个后，会在真正的全屏加载完之后才清晰化房屋
       });
      //  将图层挂到viewer上
       global.viewer.tileset=tileset
      //隐藏cesium的logo
      global.viewer._cesiumWidget._creditContainer.style.display = "none";
      //  使用viewer的scene.primitives.add()为viewer添加图层
      global.viewer.scene.primitives.add(tileset);
      // global.viewer.scene.globe.depthTestAgainstTerrain = false
      // 定位到图层
      // global.viewer.flyTo(tileset)
    },
    // 隐藏倾斜摄影
    hidden3DTiles(){
      // 移除图层
      global.viewer.scene.primitives.remove(global.viewer.tileset)
    },
    /**
     * 返回线坐标数组 
     * @param {Array} points 经纬度坐标数组
     * @return {Array} polyline位置坐标信息
     */
    getPointArr(points){
      let pointArr=new Cesium.CallbackProperty(()=>{
        return new Cesium.Cartesian3.fromDegreesArray(points)
      },false)
      return pointArr
    },
    // 展示标牌文字
    showtext(){
      const viewer = global.viewer
      // 给所有entity添加父类
      let parent1 = viewer.entities.add(new Cesium.Entity())
      // 挂载到window
      window.parent1=parent1
      // 添加广告牌1
      this.billboard('billboard_1',"billboard-1",this.strPosition[0][0], this.strPosition[0][1], 100,'#60cdad',5,3,true,20000,this.labelStr.str1,-200,-60)
      // 添加广告牌2
      this.billboard('billboard_2',"billboard-2",this.strPosition[1][0], this.strPosition[1][1], 100,'#60cdad',5,3,true,20000,this.labelStr.str2,-150,-60)
      // 添加广告牌3
      this.billboard('billboard_3',"billboard-3",this.strPosition[2][0], this.strPosition[2][1], 100,'#60cdad',5,3,true,20000,this.labelStr.str3,150,-50)
      // 添加广告牌4
      this.billboard('billboard_4',"billboard-4",this.strPosition[3][0], this.strPosition[3][1], 100,'#60cdad',5,3,true,20000,this.labelStr.str4,200,-60)
      // 添加广告牌5
      this.billboard('billboard_5',"billboard-5",this.strPosition[4][0], this.strPosition[4][1], 100,'#60cdad',5,3,true,20000,this.labelStr.str5,150,-60)
      // 添加广告牌6
      this.billboard('billboard_6',"billboard-6",this.strPosition[5][0], this.strPosition[5][1], 100,'#60cdad',5,3,true,20000,this.labelStr.str6,200,-60)
      // 添加广告牌7
      this.billboard('billboard_7',"billboard-7",this.strPosition[6][0], this.strPosition[6][1], 100,'#60cdad',5,3,true,20000,this.labelStr.str7,150,-30)
      // 添加广告牌8
      this.billboard('billboard_8',"billboard-8",this.strPosition[7][0], this.strPosition[7][1], 100,'#60cdad',5,3,true,20000,this.labelStr.str8,0,-60)
      // 添加广告牌9
      this.billboard('billboard_9',"billboard-9",this.strPosition[8][0], this.strPosition[8][1], 100,'#60cdad',5,3,true,20000,this.labelStr.str9,-200,-60)
      // 添加广告牌10
      this.billboard('billboard_10',"billboard-10",this.strPosition[9][0], this.strPosition[9][1], 100,'#60cdad',5,3,true,20000,this.labelStr.str10,180,-70)

      // 添加polyline

      this.polyline('polyline-2',this.polyLinePoints.polyline_2,3,Cesium.Color.GREEN.withAlpha(1),true,100,true)

      this.polyline('polyline-1',this.polyLinePoints.polyline_1,3,Cesium.Color.RED.withAlpha(1),true,100,true)

      this.polyline('polyline-3',this.polyLinePoints.polyline_3,3,Cesium.Color.BLUE.withAlpha(1),true,100,true)

      this.polyline('polyline-4',this.polyLinePoints.polyline_4,3,Cesium.Color.GREEN.withAlpha(1),true,100,true)

      this.polyline('polyline-5',this.polyLinePoints.polyline_5,3,Cesium.Color.RED.withAlpha(1),true,100,true)

      this.polyline('polyline-6',this.polyLinePoints.polyline_6,3,Cesium.Color.BLUE.withAlpha(1),true,100,true)

      this.polyline('polyline-7',this.polyLinePoints.polyline_7,3,Cesium.Color.GREEN.withAlpha(1),true,100,true)

      this.polyline('polyline-8',this.polyLinePoints.polyline_8,3,Cesium.Color.RED.withAlpha(1),true,100,true)

      this.polyline('polyline-9',this.polyLinePoints.polyline_9,3,Cesium.Color.BLUE.withAlpha(1),true,100,true)

      this.polyline('polyline-10',this.polyLinePoints.polyline_10,3,Cesium.Color.GREEN.withAlpha(1),true,100,true)

      this.polyline('polyline-11',this.polyLinePoints.polyline_11,3,Cesium.Color.RED.withAlpha(1),true,100,true)

      this.polyline('polyline-12',this.polyLinePoints.polyline_12,3,Cesium.Color.BLUE.withAlpha(1),true,100,true)

      this.polyline('polyline-13',this.polyLinePoints.polyline_13,3,Cesium.Color.GREEN.withAlpha(1),true,100,true)

      this.polyline('polyline-14',this.polyLinePoints.polyline_14,3,Cesium.Color.RED.withAlpha(1),true,100,true)

      this.polyline('polyline-15',this.polyLinePoints.polyline_15,3,Cesium.Color.BLUE.withAlpha(1),true,100,true)

    },
    // 控制polyline和billboard展示
    isTextShow(){
      const viewer = global.viewer
      if(this.isShow===1){
        this.showtext()
        this.isShow=0
      } else {
        viewer.entities.removeAll()
        this.isShow=1
      }
    },
    // 获取鼠标点击坐标
    getpoint(e){
      const viewer = global.viewer
      let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      handler.setInputAction(function(event){
          let ray = viewer.camera.getPickRay(event.position);
          // console.log(ray,'ray');
          let cartesian = viewer.scene.globe.pick(ray, viewer.scene);
          // console.log(cartesian,'cartesian');
          let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
          let lng = Cesium.Math.toDegrees(cartographic.longitude); // 经度
          let lat = Cesium.Math.toDegrees(cartographic.latitude); // 纬度
          let alt = cartographic.height; // 高度
          let coordinate = {
              longitude: Number(lng.toFixed(6)),
              latitude: Number(lat.toFixed(6)),
              altitude: Number(alt.toFixed(2))
          };
          console.log(coordinate);
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    },
    // 展示淹没分析面板
     showFlood(){
      this.showFlowTool=!this.showFlowTool
     },
    // 隐藏淹没分析面板
    hideFlood(){
      this.showFlowTool=!this.showFlowTool
      global.viewer.entities.removeAll()
      this.maxFlood=0
      this.miniFlood=0
      this.nowFlood=0
      window.adapCoordi=[]
      this.speed=0.5
      this.per=0
      global.isActive1=!global.isActive1
     },
    drawFlowingPolygon() {
      const flowing_draw = new SubmergenceAnalysis()
    },
    showactive1(){
      this.isChange1=!this.isChange1
    },
    showactive2(){
      this.isChange2=!this.isChange2
    },
    showactive3(){
      this.isChange3=!this.isChange3
    },
    draw_polygon() {
      this.$message('单击左键绘制范围，右键结束')
      const viewer = global.viewer
      const _this = this
      var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
      // 取消双击事件-追踪该位置
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
      // 鼠标事件
      handler = new Cesium.ScreenSpaceEventHandler(
        viewer.scene._imageryLayerCollection
      )
      var positions = []
      var tempPoints = []
      var polygon = null
      var cartesian = null
      var floatingPoint
      var measureFeature_polygon = []
      var adapCoordi = []
      var maxHeight = []
      var getHei=[]
 
      handler.setInputAction(function (movement) {
        const ray = viewer.camera.getPickRay(movement.endPosition)
        cartesian = viewer.scene.globe.pick(ray, viewer.scene)
        // cartesian = window.viewer.scene.camera.pickEllipsoid(movement.endPosition, window.viewer.scene.globe.ellipsoid);
        if (positions.length >= 2) {
          if (!Cesium.defined(polygon)) {
            polygon = new PolygonPrimitive(positions)
          } else {
            positions.pop()
            positions.push(cartesian)
          }
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
 
      handler.setInputAction(function (movement) {
        const ray = viewer.camera.getPickRay(movement.position)
        cartesian = viewer.scene.globe.pick(ray, viewer.scene)
        // cartesian = window.viewer.scene.camera.pickEllipsoid(movement.position, window.viewer.scene.globe.ellipsoid);
        if (positions.length == 0) {
          positions.push(cartesian.clone())
        }
        // positions.pop();
        positions.push(cartesian)
        // 在三维场景中添加点
        var cartographic = Cesium.Cartographic.fromCartesian(
          positions[positions.length - 1]
        )
        var longitudeString = Cesium.Math.toDegrees(cartographic.longitude)
        var latitudeString = Cesium.Math.toDegrees(cartographic.latitude)
        var heightString = cartographic.height
        tempPoints.push({
          lon:longitudeString,
          lat:latitudeString,
          hei:heightString
        })
        adapCoordi.push(longitudeString,latitudeString,0)
        getHei.push(longitudeString,latitudeString,heightString)
        // 汇总所有高程
        maxHeight.push(heightString)
        window.adapCoordi=adapCoordi
        window.maxHeight=maxHeight
        window.tempPoints=tempPoints
        window.getHei=getHei
        // tempPoints.push(longitudeString)
        // tempPoints.push(latitudeString)
        // getHight(tempPoints)
        floatingPoint = viewer.entities.add({
          name: '多边形面积',
          position: positions[positions.length - 1],
          point: {
            pixelSize: 5,
            color: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.DEEPSKYBLUE,
            outlineWidth: 3
          }
        })
        measureFeature_polygon.push(  )
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
 
      handler.setInputAction(function (movement) {
        handler.destroy()
        positions.pop()
        var polyCenter = Cesium.BoundingSphere.fromPoints(positions).center
        var textArea = getArea(window.tempPoints) + 'km²'
        const _label = viewer.entities.add({
          name: '多边形面积',
          position: polyCenter,
          // position: positions[positions.length - 1],
          label: {
            text: textArea,
            font: '16px sans-serif',
            fillColor: Cesium.Color.DARKORANGE,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
          }
        })
        measureFeature_polygon.push(_label)
        // 绘制范围按钮颜色变回默认

        _this.isChange3=false
        let floodArr = []
        window.tempPoints.forEach((item)=>{
          floodArr.push(item.hei)
        })
        floodArr.sort()
        // 求最大高程
        let targetHeight=floodArr[floodArr.length-1].toFixed(2)-0
        // 求最小高程
        let minFlood=floodArr[0].toFixed(2)-0
        _this.maxFlood=targetHeight
        _this.miniFlood=minFlood
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
 
      var radiansPerDegree = Math.PI / 180.0 // 角度转化为弧度(rad)
      var degreesPerRadian = 180.0 / Math.PI // 弧度转化为角度
 
      // 计算多边形面积
      function getArea(points) {
        var res = 0
        // 拆分三角曲面
        for (var i = 0; i < points.length - 2; i++) {
          var j = (i + 1) % points.length
          var k = (i + 2) % points.length
          var totalAngle = Angle(points[i], points[j], points[k])
 
          var dis_temp1 = distance(positions[i], positions[j])
          var dis_temp2 = distance(positions[j], positions[k])
          res += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle))
          console.log(res)
        }
 
        return (res / 1000000.0).toFixed(4)
      }
      function logPosition (position) {
        var ray = viewer.camera.getPickRay(position)
        var cartesian = viewer.scene.globe.pick(ray, viewer.scene)
        var cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(cartesian)
        var long2 = Cesium.Math.toDegrees(cartographic.longitude)
        var lat2 = Cesium.Math.toDegrees(cartographic.latitude)
        console.log(long2 + ',' + lat2)
      }
 
      /* 角度 */
      function Angle(p1, p2, p3) {
        var bearing21 = Bearing(p2, p1)
        var bearing23 = Bearing(p2, p3)
        var angle = bearing21 - bearing23
        if (angle < 0) {
          angle += 360
        }
        return angle
      }
      /* 方向 */
      function Bearing(from, to) {
        var lat1 = from.lat * radiansPerDegree
        var lon1 = from.lon * radiansPerDegree
        var lat2 = to.lat * radiansPerDegree
        var lon2 = to.lon * radiansPerDegree
        var angle = -Math.atan2(
          Math.sin(lon1 - lon2) * Math.cos(lat2),
          Math.cos(lat1) * Math.sin(lat2) -
            Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2)
        )
        if (angle < 0) {
          angle += Math.PI * 2.0
        }
        angle = angle * degreesPerRadian // 角度
        return angle
      }
 
      var PolygonPrimitive = (function () {
        function _(positions) {
          this.options = {
            name: '多边形',
            polygon: {
              hierarchy: [],
              // perPositionHeight : true,
              material: new Cesium.Color(0, 124 / 255, 247 / 255, 0.2)
              // material: Cesium.Color.GREEN.withAlpha(0.5)
              // heightReference:20000
            }
          }
 
          this.hierarchy = { positions }
          this._init()
        }
 
        _.prototype._init = function () {
          var _self = this
          var _update = function () {
            return _self.hierarchy
          }
          // 实时更新polygon.hierarchy
          this.options.polygon.hierarchy = new Cesium.CallbackProperty(
            _update,
            false
          )
          const _polygon = viewer.entities.add(this.options)
          window._polygon=_polygon
          measureFeature_polygon.push(_polygon)
          this.measureFeature_polygon=measureFeature_polygon
          // console.log(this.measureFeature_polygon);
        }
 
        return _
      })()
 
      function distance(point1, point2) {
        var point1cartographic = Cesium.Cartographic.fromCartesian(point1)
        var point2cartographic = Cesium.Cartographic.fromCartesian(point2)
        /** 根据经纬度计算出距离**/
        var geodesic = new Cesium.EllipsoidGeodesic()
        geodesic.setEndPoints(point1cartographic, point2cartographic)
        var s = geodesic.surfaceDistance
        // 返回两点之间的距离
        s = Math.sqrt(
          Math.pow(s, 2) +
            Math.pow(point2cartographic.height - point1cartographic.height, 2)
        )
        return s
      }

    },
    // 水淹分析效果
    startFlowing(){   //targetHeight 目标高度 adapCoordi 范围坐标 waterHeight当前水高度
      let _this=this
      const viewer = global.viewer
      _this.active = true
      // 将进度条初始化
      _this.per=0
      window.speed=_this.speed
      // 判断是否已经创建好面
      if(window.tempPoints.length<3){
        this.$message('请单击左键绘制范围')
        return
      }
      // 默认起始高度为最小高程
      let waterHeight=_this.miniFlood-0
      let targetHeight=_this.tarFlood
      this.nowFlood=waterHeight
      // 目标高程不可低于实际最小高程
      if(targetHeight<_this.miniFlood||targetHeight>_this.maxFlood){
        this.$message('目标淹没高度不可小于最低高程且不能大于最大高程')
        return
      }
      
      // 删除绘制好的范围
      viewer.entities.remove(window._polygon)
      var entities = viewer.entities;
      // 判断是否绘制过
      let y =viewer.entities.getById('yanmo')
      if(y){
        viewer.entities.remove(y)
      }
      let flood = entities.add({
        id:'yanmo',
        polyline: {
        positions: window.adapCoordi,
        width: 0.5,
        material: new Cesium.Color.fromBytes(0,191,255,100),
        clampToGround: true,
        },
        polygon : {
          hierarchy : new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArrayHeights(window.getHei)),
          perPositionHeight: true,
          extrudedHeight: new Cesium.CallbackProperty(function () {  //此处用属性回调函数，直接设置extrudedHeight会导致闪烁。
            if(_this.active == true) {
              waterHeight+=(window.speed/15)-0
              _this.video=false
              _this.pause1=true
              // 取两位小数
              waterHeight=Math.floor(waterHeight*100)/100-0
              _this.nowFlood=waterHeight-0
              // 判断是否到达最大值
              if(waterHeight>targetHeight){
                waterHeight=targetHeight-0;//给个最大值
                _this.video=true
                _this.pause1=false
                _this.active=false
                // _this.sleep(1000/_this.speed)
              }
            }else{
              _this.video=true
              _this.pause1=false
              _this.active=false
            }
            return waterHeight
            },false),
          material : new Cesium.Color.fromBytes(0,191,255,100),
          closeTop: false,
          heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
          clampToGround: true,
          zIndex:1000
        },
      })
    },
    // 指定时间内强制等待
    sleep(time) {
      var startTime = new Date().getTime() + parseInt(time, 10);
      while(new Date().getTime() < startTime) {}
      },
    // 清除淹没分析
    clearFlowing() {
      global.viewer.entities.removeAll()
      this.maxFlood=0
      this.miniFlood=0
      this.nowFlood=0
      window.adapCoordi=[]
      this.speed=0.5
      this.per=0-0
      this.tarFlood=0
      console.log(this.per);
    },
    // 开始播放
    start(){
      this.active=true
      this.video=false
      this.pause1=true
    },
    // 暂停播放
    pause(){
      console.log('暂停');
      this.active=false
      this.video=true
      this.pause1=false
    },
    // 拖拽函数
    formatTooltip(val) {
      const viewer = global.viewer
      let yanmo = viewer.entities.getById('yanmo')
      if(yanmo){
        let dragFlood =val*((this.tarFlood-this.miniFlood)/100)+this.miniFlood
        yanmo.extrudedHeight= dragFlood
        this.nowFlood=dragFlood
        this.per=val
      }
    },
  },
  watch:{
    nowFlood:function(newPer){
      const _this= this
      if(newPer===0){
        _this.per=0
        return
      }
      let percent = ((newPer-_this.miniFlood)/(_this.tarFlood-_this.miniFlood))*100
      _this.per=percent.toFixed(2)-0
    },
  }
}
  

</script>

<style scoped>
.box{
  position: relative;
}
#container{
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0;
}
.flood{
  position: absolute;
  top: 15vh;
  left: 75vw;
  z-index: 999;
  width: 18vw;
  background-color: rgba(0, 0, 0,0.2);
  color: white;
  height: 44vh;
  border: solid 1px #60cdad;
  display: flex;
  flex-direction: column;
  padding: 1vw;
  padding-top: 5vh;
  font-size: 1.7vh;
  box-sizing: border-box;
}
.el-icon-close{
  position: absolute;
  right: 0.1vw;
  top: 1vh;
  cursor: pointer !important;
  z-index: 100;
}
.btns {
  display: flex;
  justify-content: space-between;
  padding: 5px;
  width: 100%;
  color: black; 
  margin: 2px;
  cursor: pointer !important;
  z-index: 999;
  margin-top: 6px;
}
button{
  border: 1px solid #555758;
  background-color: rgba(255, 255, 255,1);
  border-radius: 5px;
  height: 4vh;
  margin-bottom: 2vw;
  margin-right: 1vw;
  width: 4vw;
}
label {
  margin: 1vh 0px 1vh 1vh;
  color: rgb(221, 218, 218);
  text-align: left;
}
input {
  width: 9vw;
  margin-left: 0.5vw;
}
.active{
  background-color: lightgray;
}
.unactive{
  background-color: white;;
}
.video{
  position: absolute;
  top: 50rem;
  left:50rem;
  z-index: 999;
}
.flood-item{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin-bottom: 10px;
}
#btn3{
  margin-left: 0px;
  width: 6vw;
}
.i{
  margin-top: 10px;
}
.block{
  position: absolute;
  top: 87vh;
  left: 40vw;
  z-index: 999;
  display: flex;
}
.long{
  width: 20vw;
}
i{
  font-size: 3.5vh;
  margin-right: 0.5vw;
  line-height: 4vh;
  color:rgb(96, 205, 173); 

}
.long2{
  font-size: 2.5vh;
  margin-left: 1vw;
  line-height: 4.5vh;
  color:rgb(96, 205, 173); 
}
.controler{
  height: 100%;
}
</style>